package com.hwh.bootdemoweb.Netty第四章.Netty第五章;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

import static com.hwh.bootdemoweb.ByteBufferUtil.debugAll;

/**
 * @author wenhao hu
 * @title: MultiThreadServer
 * @projectName bootdemoweb
 * @description: TODO
 * @date 2021/12/1414:21
 */
public class MultiThreadServer {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        //创建Selector 管理多个Channel
        Selector boss = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        //建立Selector和Channel的联系，注册channel到Selector
        //SelectionKey:事件发生时通过它可以得到这个事件和哪个channel发送的事件
        SelectionKey bossKey = ssc.register(boss, 0, null);
        //key 只关注accept事件
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));
        //创建固定数量的worker并初始化
        Worker worker = new Worker("worker-0");
        while (true) {
            boss.select();
            //处理事件 selectedKeys内部包含了所有发生的事件
            Iterator<SelectionKey> iterator = boss.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                //区分事件类型
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    System.out.println("connected...."+sc.getRemoteAddress());
                    //关联register
                    System.out.println("before register"+sc.getRemoteAddress());
                    worker.register();
                    sc.register(worker.selector,SelectionKey.OP_READ,null);
                    System.out.println("after register"+sc.getRemoteAddress());
                }
            }
        }
    }

    static class Worker implements Runnable {
        private Thread thread;
        private Selector selector;
        private String name;
        private volatile boolean start = false; //初始化标识

        public Worker(String name) {
            this.name = name;
        }

        public void register() throws IOException {
            if (!start){
                thread = new Thread(this, name);
                thread.start();
                selector = Selector.open();
                start = true;
            }
        }

        @Override
        public void run() {
            while (true) {
                try {
                    selector.select();
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isReadable()){
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            channel.read(buffer);
                            buffer.flip();
                            debugAll(buffer);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
